package com.rou.im.boot.starter.server.netty;

import com.rou.im.boot.starter.server.ChannelInitializerPostProcessor;
import com.rou.im.boot.starter.server.netty.config.NettyConfigProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.logging.LoggingHandler;
import org.springframework.beans.factory.FactoryBean;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2020-05-03 23:38
 */

public class ServerBootstrapBean implements FactoryBean<ServerBootstrap>{

   private final NettyConfigProperties nettyConfig;

   private final EventLoopGroupManager manager;

   private final ServerSocketChannelSelector serverSocketChannelSelector;


   private final ChannelInitializerPostProcessor channelInitializerPostProcessor;
    public ServerBootstrapBean(NettyConfigProperties nettyConfig, EventLoopGroupManager manager, ServerSocketChannelSelector serverSocketChannelSelector, ChannelInitializerPostProcessor channelInitializerPostProcessor) {
        this.nettyConfig = nettyConfig;
        this.manager = manager;
        this.serverSocketChannelSelector = serverSocketChannelSelector;
       // this.channelInitializer = channelInitializer;
        this.channelInitializerPostProcessor = channelInitializerPostProcessor;
    }

    @Override
    public ServerBootstrap getObject() throws Exception {
        ServerBootstrap b = new ServerBootstrap();
        b.group(manager.getBossGroup(), manager.getWorkerGroup())
                .channel(serverSocketChannelSelector.selector(nettyConfig.getServer().getIoType()));
        //.childHandler(protocolInitalizer);
        Map<ChannelOption<?>, Object> options = new HashMap<>();
        options.put(ChannelOption.SO_KEEPALIVE, nettyConfig.getOption().isKeepAlive());
        options.put(ChannelOption.SO_BACKLOG, nettyConfig.getOption().getBacklog());
        Set<ChannelOption<?>> keySet = options.keySet();
        for (ChannelOption option : keySet) {
            b.option(option, options.get(option));
        }
        if(nettyConfig.getHandler().getLogLevel()!=null){
            b.handler(new LoggingHandler(nettyConfig.getHandler().getLogLevel()));
        }
        b.localAddress(nettyConfig.getServer().getPort());
        b.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                channelInitializerPostProcessor.initChannelPostProcessor(ch);
            }
        });
        return b;
    }

    @Override
    public Class<?> getObjectType() {
        return ServerBootstrap.class;
    }


}
